<?php

// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("otafood") or die(mysql_error());

// Get the http GET parameters
$action = $_GET["action"];
$id = $_GET["id"];
$name = $_GET["name"];
$restaurant = $_GET["restaurant"];

$year = $_GET["year"];
$month = $_GET["month"];
$day = $_GET["day"];
$hour = $_GET["hour"];
$minute = $_GET["minute"];

$key = 'You can never guess me';

$td = mcrypt_module_open ('des', '', 'ecb', ''); 
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND); 
mcrypt_generic_init ($td, $key, $iv); 
$decodedId = base64_decode($id);
$id_decrypt = mdecrypt_generic ($td, $decodedId); 

mcrypt_generic_init ($td, $key, $iv); 
$decodedName = base64_decode($name);
$name_decrypt = mdecrypt_generic ($td, $decodedName); 

$trimmed = preg_replace('/[^(\x20-\x7F)]*/','', $id_decrypt);
$response = file_get_contents("http://graph.facebook.com/". $trimmed . "?fields=name");
$arr = json_decode($response);
$name_facebook = preg_replace('/[^(\x20-\x7F)]*/','', $arr->{"name"});

// Check if the facebook id is valid
if($name_facebook === preg_replace('/[^(\x20-\x7F)]*/','', $name_decrypt)){

	if($action === "del") {
		$reservation_time = $year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute . ":00";
		mysql_query('DELETE from book WHERE id_facebook=' . preg_replace('/[^(\x20-\x7F)]*/','', $id_decrypt) . ' AND time=\'' . $reservation_time . '\'');
	}
	
	else if($action === "add") {
		$reservation_time = $year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute . ":00";
		mysql_insert('book', array(
			'id_facebook' => preg_replace('/[^(\x20-\x7F)]*/','', $id_decrypt),
			'restaurant' => $restaurant,
			'time' => $reservation_time
		));
	}
	
	else
		echo "Invalid action.";
}
else
	echo "Invalid facebook id."	;


// Insert function for general mysql INSERT
function mysql_insert($table, $inserts) {
    $values = array_map('mysql_real_escape_string', array_values($inserts));
    $keys = array_keys($inserts);
       
	//echo 'INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')';
    return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}

?>
